package com.lczyfz.wisdom.modules.platform.vueweb;

import com.lczyfz.wisdom.common.utils.StringUtils;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.logging.Logger;

/**
 * Create by css on 2019/9/28
 */

@Api(value = "check",description = "微信授权接口")
@RestController
@RequestMapping(value = "${apiPath}/check/check")
public class VueCheckController {
    private static final Logger logger = Logger.getLogger("platform.modules.vueweb.VueCheckController.class");

    private static String WX_TOKEN = "css123456";

    @RequestMapping(value = "wx_token", method = RequestMethod.GET)
    public String token(HttpServletRequest request, HttpServletResponse response){
        PrintWriter writer = null;
        String result = null;
        try{
            String singature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");

            String[] arr = {WX_TOKEN,timestamp,nonce};
            Arrays.sort(arr);
            String str = arr[0]+arr[1]+arr[2];
            if(StringUtils.isNotBlank(singature) && StringUtils.isNotBlank(timestamp)
                && StringUtils.isNotBlank(nonce) && StringUtils.isNotBlank(echostr)){
                result = valid(str);
            }
            if(result.equalsIgnoreCase(singature)){
                return echostr;
            }
            logger.info("微信singature "+singature);
            logger.info("my singature "+result);

        }catch (Exception e){
            logger.info("验证token异常");
            return "";
        }
        return "";
    }

    public static String valid(String src){

        StringBuilder before = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("sha1");
            byte[] digest = md.digest(before.toString().getBytes());
            char[] chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            for(byte b:digest){
                before.append(chars[(b>>4)&15]);
                before.append(chars[b&15]);
            }
            return before.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

}
